//
//  SetViewController.m
//  PetApp
//
//  Created by apple on 16/3/11.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "SetViewController.h"
#import "ModelOfUserinfo.h"
#import <YYWebImage.h>
#import "NetworkingHandle.h"
#import <DKNightVersion.h>
#import "CellOfMySetForSet.h"
#import "DataBaseHandle.h"
#import "RESideMenu.h"

@interface SetViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) RESideMenu *sideMenuViewController;

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) UIView *viewOfTableViewHeader;

@property (nonatomic, retain) UIImageView *imageViewOfFace;

@property (nonatomic, retain) UILabel *labelOfName;

@property (nonatomic, retain) ModelOfUserinfo *modelOfUser;

@property (nonatomic, retain) NSArray *imageArr;

@property (nonatomic, retain) UILabel *labelOfLogin;

@property (nonatomic, retain) UILabel *labelOfCache;

@property (nonatomic, retain) UISwitch *switchOfNight;

@end

@implementation SetViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"handleData"];
    [_sideMenuViewController release];
    [_labelOfLogin release];
    [_tableView release];
    [_viewOfTableViewHeader release];
    [_imageViewOfFace release];
    [_labelOfName release];
    [_modelOfUser release];
    [_imageArr release];
    [super dealloc];
}

- (RESideMenu *)sideMenuViewController {
    UIViewController *iter = self.parentViewController;
    while (iter) {
        if ([iter isKindOfClass:[RESideMenu class]]) {
            return (RESideMenu *)iter;
        } else if (iter.parentViewController && iter.parentViewController != iter) {
            iter = iter.parentViewController;
        } else {
            iter = nil;
        }
    }
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createSubViews];
    [self handleData];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"handleData" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [self handleData];
    }];


}

- (void)handleData {
    
    [NetworkingHandle handleWorkData:@"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=getUserInfoByUid" AndBody:[NSString stringWithFormat: @"service=getUserInfoByUid&sign=1fb52759325a5de80ce1472c2b2a6966&uid=%@&version=d1bd83a33f1a841ab7fda32449746cc4", [[NSUserDefaults standardUserDefaults] stringForKey:@"uid"]] value:@{@"Content-Type" : @"application/x-www-form-urlencoded"} handleBlock:^(id result) {
        
        NSDictionary *tempDic = [result objectForKey:@"userinfo"];
        _modelOfUser = [[ModelOfUserinfo alloc] init];
        
        [self.modelOfUser setValuesForKeysWithDictionary:tempDic];
        [self changeHeaderViewContentWithModel:self.modelOfUser];
        
    }];
    
    
}


- (void)createSubViews {
    
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 9 * 1.5, self.view.frame.size.width / 6 * 4, self.view.frame.size.height / 9 * 6) style:UITableViewStylePlain];
        tableView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.opaque = NO;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView = nil;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.bounces = NO;
        tableView;
    });
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    [self.tableView registerClass:[CellOfMySetForSet class] forCellReuseIdentifier:@"poolOfCell"];
    
    [self createHeaderViewWithFrame:self.tableView.frame];

}

- (void)createHeaderViewWithFrame:(CGRect)frame {
    
    self.viewOfTableViewHeader = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 200)] autorelease];
    
    self.viewOfTableViewHeader.backgroundColor = [UIColor clearColor];
    
    self.tableView.tableHeaderView = self.viewOfTableViewHeader;
    
    self.imageViewOfFace = [[UIImageView alloc] initWithFrame:CGRectMake(40, 0, 100, 100)];
    [self.viewOfTableViewHeader addSubview:_imageViewOfFace];
    [_imageViewOfFace release];
    self.imageViewOfFace.layer.cornerRadius = 50;
    self.imageViewOfFace.layer.masksToBounds = YES;
    self.imageViewOfFace.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tapOfFace = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleLoginWithTap:)];
    [self.imageViewOfFace addGestureRecognizer:tapOfFace];
    [tapOfFace release];
    
    
    
    self.labelOfName = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMidX(self.imageViewOfFace.frame) - 75, 110, 150, 30)];
    [self.viewOfTableViewHeader addSubview:_labelOfName];
    [_labelOfName release];
    self.labelOfName.font = [UIFont systemFontOfSize:17];
    self.labelOfName.userInteractionEnabled = YES;
    self.labelOfName.text = @"未登录";
    self.labelOfName.textAlignment = NSTextAlignmentCenter;
    self.labelOfName.textColor = [UIColor blackColor];
    
    
    
    
    
}

- (void)handleLoginWithTap:(UITapGestureRecognizer *)tap {
    
    
    if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"loginState"] boolValue]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PushLoginVC" object:nil userInfo:@{@"model" : self.modelOfUser}];
        [self.sideMenuViewController hideMenuViewController];
        
    }else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PushLoginVC" object:nil userInfo:nil];
        [self.sideMenuViewController hideMenuViewController];
        
    }
    
    
}

- (void)changeHeaderViewContentWithModel:(ModelOfUserinfo *)model {
    if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"loginState"] boolValue]) {
        [self.imageViewOfFace yy_setImageWithURL:[NSURL URLWithString:model.picbig] options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation];
        self.labelOfName.text = model.username;
    }else {
        self.imageViewOfFace.image = [UIImage imageNamed:@"zhanweitu"];
        self.labelOfName.text = @"未登录";
    }
    
    
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清除缓存" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            YYImageCache *cache = [YYWebImageManager sharedManager].cache;
            [cache.memoryCache removeAllObjects];
            [cache.diskCache removeAllObjects];
            
            //创建对象
            NSFileManager *manage = [NSFileManager defaultManager];
            
            //设置文件夹路径
            NSString *dir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Cache"];
            // 删除文件夹(目录)
            [manage removeItemAtPath:dir error:nil];
            //创建目录
            [manage createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
            
            //删除历史搜索
            [[DataBaseHandle shareDataBaseHandle] updateSQL:@"DROP TABLE history"];
            //创建SQL语句.
            NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS history(number INTEGER PRIMARY KEY AUTOINCREMENT, content text)";
            [[DataBaseHandle shareDataBaseHandle] updateSQL:createTableSQL];
            self.labelOfCache.text = @"0 K";
            
        }];
        
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:actionCancel];
        [alert addAction:actionOK];
        
        //  模态推出.
        [self presentViewController:alert animated:YES completion:^{}];
        
    }


}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *titles = @[@"夜间模式", @"清理缓存"];
    CellOfMySetForSet *cell = [tableView dequeueReusableCellWithIdentifier:@"poolOfCell"];
    cell.labelOfTitle.text = titles[indexPath.row];
    
    if (indexPath.row == 1) {
        self.labelOfCache = [[UILabel alloc] initWithFrame:CGRectMake(self.tableView.frame.size.width - 125, 10, 90, 30)];
        [cell.contentView addSubview:_labelOfCache];
        [_labelOfCache release];
        self.labelOfCache.textAlignment = NSTextAlignmentRight;
        YYImageCache *cache = [YYWebImageManager sharedManager].cache;
        if (cache.diskCache.totalCount < 1024) {
            self.labelOfCache.text = [NSString stringWithFormat:@"%ld K", cache.diskCache.totalCount];
        }else{
            self.labelOfCache.text = [NSString stringWithFormat:@"%.2f M", cache.diskCache.totalCount / 1024.f];
        }
        /**
         // 获取缓存大小
         cache.memoryCache.totalCost;
         cache.memoryCache.totalCount;
         cache.diskCache.totalCost;
         cache.diskCache.totalCount;
         
         // 清空缓存
         [cache.memoryCache removeAllObjects];
         [cache.diskCache removeAllObjects];
         
         // 清空磁盘缓存，带进度回调
         [cache.diskCache removeAllObjectsWithProgressBlock:^(int removedCount, int totalCount) {
         // progress
         } endBlock:^(BOOL error) {
         // end
         }];
         */
        
        
    }else if (indexPath.row == 0) {
        self.switchOfNight = [[UISwitch alloc] initWithFrame:CGRectMake(self.tableView.frame.size.width - 70, 10, 0, 0)];
        [cell.contentView addSubview:_switchOfNight];
        [_switchOfNight release];
        
        self.switchOfNight.onTintColor = [UIColor clearColor];
        self.switchOfNight.tintColor = [UIColor clearColor];
        self.switchOfNight.layer.borderWidth = 1;
        self.switchOfNight.layer.cornerRadius = self.switchOfNight.frame.size.height / 2.0f;
        
        
        
        [self.switchOfNight addTarget:self action:@selector(handleSwitch:) forControlEvents:UIControlEventValueChanged];
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"ISNIGHT"]) {
            self.switchOfNight.on = YES;
        }else {
            self.switchOfNight.on = NO;
            
        }
        
    }
    
    return cell;
}

- (void)handleSwitch:(UISwitch *)SWIT {
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    if ([DKNightVersionManager currentThemeVersion] == DKThemeVersionNight) {
        [DKNightVersionManager dawnComing];
    } else {
        [DKNightVersionManager nightFalling];
    }
    // 保存状态 , 程序再次启动时的偏好设置
    [user setBool:SWIT.on forKey:@"ISNIGHT"];
    [user synchronize];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SwitchChange" object:nil userInfo:@{@"switch" : @(SWIT.on)}];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
